package com.jjh.jhwebserver.core;

import com.jjh.jhwebserver.handler.JhRequestHandler;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.*;

/**
 * @author JJH
 */
public class ServerSocketHandler {

    private ServletContext context;

    private int port =8080;

    public ServerSocketHandler(ServletContext context){
        this.context = context;
        this.start(this.context);
    }
    public ServerSocketHandler(ServletContext context,int port){
        this.context = context;
        this.port = port;
        this.start(this.context);
    }




    public void start(ServletContext context) {
        ServerSocket serverSocket;
        try {

            serverSocket = new ServerSocket(this.port);
            System.out.println("JHWebServer start success! Listening port: "+this.port);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        //换成线程池来处理，更加高效
        ThreadPoolExecutor pool =
                new ThreadPoolExecutor(10,15,30, TimeUnit.SECONDS,new LinkedBlockingDeque<>());

        //只要服务器没有关闭，就一直运行
        while (!serverSocket.isClosed()){
            //接受客户端发来的请求
            Socket socket ;
            try {
                socket = serverSocket.accept();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            //将socket交给线程处理
           // new Thread(new JhRequestHandler(socket)).start();
            pool.submit(new JhRequestHandler(socket,context));
        }

    }

}
